package club.martaintao.activiti7springbootdemo.config;

import club.martaintao.activiti7springbootdemo.model.LocalUserDetail;
import club.martaintao.activiti7springbootdemo.model.entity.User;
import club.martaintao.activiti7springbootdemo.service.mapper.UserDynamicSqlSupport;
import club.martaintao.activiti7springbootdemo.service.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;

import java.util.Optional;

import static org.mybatis.dynamic.sql.SqlBuilder.isEqualTo;

@Component
public class CustomUserDetailService implements UserDetailsService {

    @Autowired
    UserMapper userMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<User> user = userMapper.selectOne(c -> c.where(UserDynamicSqlSupport.username, isEqualTo(username)));
        if (!user.isPresent()){
           throw new UsernameNotFoundException("用户不存在");
        }
        User u = user.get();
        return LocalUserDetail.of(u);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

}
